home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1998 August: Tool Chest / Dev.CD Aug 98 TC.toast / Sample Code / Networking / OTSimpleServerHTTP1.2d2 / OTSimpleServerHTTP.c < prev    next >
Encoding:
Text File  |  1997-08-27  |  22.3 KB  |  732 lines  |  [TEXT/CWIE]

  1. /*
  2.     File:        OTSimpleServerHTTP.c
  3.  
  4.     Contains:    Implementation of the simple HTTP server sample.
  5.  
  6.     Written by:    Quinn "The Eskimo!"
  7.  
  8.     Copyright:    © 1997 by Apple Computer, Inc., all rights reserved.
  9.  
  10.     Change History (most recent first):
  11.     
  12.     08/27/97 - Rich Kubota - Included call to DoNegotiateIPReuseAddrOption
  13.                 so that on each endpoint, the IP level ReuseAddr option
  14.                 is enabled so that on immediate relaunch of the application,
  15.                 the designated IP addresses could be reused without IP
  16.                 protecting them until the timeout occurs.
  17.  
  18.     You may incorporate this sample code into your applications without
  19.     restriction, though the sample code has been provided "AS IS" and the
  20.     responsibility for its operation is 100% yours.  However, what you are
  21.     not permitted to do is to redistribute the source as "DSC Sample Code"
  22.     after having made changes. If you're going to re-distribute the source,
  23.     we require that you make it clear in the source that the code was
  24.     descended from Apple Sample Code, but that you've made changes.
  25. */
  26.  
  27. /////////////////////////////////////////////////////////////////////
  28. // The OT debugging macros in <OTDebug.h> require this variable to
  29. // be set.
  30.  
  31. #ifndef qDebug
  32. #define qDebug    1
  33. #endif
  34.  
  35. /////////////////////////////////////////////////////////////////////
  36. // Pick up all the standard OT stuff.
  37.  
  38. #include <OpenTransport.h>
  39.  
  40. /////////////////////////////////////////////////////////////////////
  41. // Pick up all the OT TCP/IP stuff.
  42.  
  43. #include <OpenTptInternet.h>
  44.  
  45. /////////////////////////////////////////////////////////////////////
  46. // Pick up the OTDebugBreak and OTAssert macros.
  47.  
  48. #include <OTDebug.h>
  49.  
  50. /////////////////////////////////////////////////////////////////////
  51. // Pick up the various Thread Manager APIs.
  52.  
  53. #include <Threads.h>
  54.  
  55. /////////////////////////////////////////////////////////////////////
  56.  
  57. #include <stdio.h>
  58.  
  59. /////////////////////////////////////////////////////////////////////
  60. // Pick up our own prototype.
  61.  
  62. #include "OTSimpleServerHTTP.h"
  63.  
  64. /////////////////////////////////////////////////////////////////////
  65. // OTDebugStr is not defined in any OT header files, but it is
  66. // exported by the libraries, so we define the prototype here.
  67.  
  68. extern pascal void OTDebugStr(const char* str);
  69.  
  70. /////////////////////////////////////////////////////////////////////
  71. // When this boolean is to set true, this module assumes that the
  72. // host application is trying to quit and all the threads created by
  73. // this module start dying.  See the associated comment in the
  74. // YieldingNotifier routine.
  75.  
  76. extern Boolean gQuitNow = false;
  77.  
  78. // RRK Comments added 8/27/97
  79. // DoNegotiateIPReuseAddrOption is defined in the file
  80. // EnableIPReuseAddrSample.c.  This call uses the OTOptionManagement function
  81. // to set the IP level ResuseAddr option so that an IP address can be
  82. // reused on immediate relaunch of the application.
  83. extern OSStatus DoNegotiateIPReuseAddrOption(EndpointRef ep, Boolean enableReuseIPMode);
  84.  
  85. /////////////////////////////////////////////////////////////////////
  86.  
  87. static pascal void YieldingNotifier(EndpointRef ep, OTEventCode code, 
  88.                                        OTResult result, void* cookie)
  89.     // This simple notifier checks for kOTSyncIdleEvent and
  90.     // when it gets one calls the Thread Manager routine
  91.     // YieldToAnyThread.  Open Transport sends kOTSyncIdleEvent
  92.     // whenever it's waiting for something, eg data to arrive
  93.     // inside a sync/blocking OTRcv call.  In such cases, we
  94.     // yield the processor to some other thread that might
  95.     // be doing useful work.
  96.     //
  97.     // The routine also checks the gQuitNow boolean to see if the
  98.     // the host application wants us to quit.  This roundabout technique
  99.     // avoids a number of problems including:
  100.     //
  101.     // 1. Threads stuck inside OT synchronous calls -- You can't just
  102.     //    call DisposeThread on a thread that's waiting for an OT
  103.     //    synchronous call to complete.  Trust me, it would be bad!
  104.     //    Instead, this routine calls OTCancelSynchronousCalls to get
  105.     //    out of the call.  The given error code (userCanceledErr) 
  106.     //    propagates out to the caller, which causes the calling
  107.     //    thread to eventually terminate.
  108.     // 2. Threads holding resources -- You can't just DisposeThread
  109.     //    a networking thread because it might be holding resouces,
  110.     //    like memory or endpoints, that need to be cleaned up properly.
  111.     //    Cancelling the thread in this way causes the thread's own
  112.     //    code to clean up those resources just like it would for any
  113.     //    any other error.
  114.     //
  115.     // I could have used a more sophisticated mechanism to support
  116.     // quitting (such as a boolean per thread, or returning some
  117.     // "thread object" to which the application can send a "cancel"
  118.     // message, but this way is easy and works just fine for this
  119.     // simple sample
  120. {
  121.     #pragma unused(result)
  122.     #pragma unused(cookie)
  123.     OSStatus junk;
  124.     
  125.     switch (code) {
  126.         case kOTSyncIdleEvent:
  127.             junk = YieldToAnyThread();
  128.             OTAssert("YieldingNotifier: YieldToAnyThread failed", junk == noErr);
  129.             
  130.             if (gQuitNow) {
  131.                 junk = OTCancelSynchronousCalls(ep, userCanceledErr);
  132.                 OTAssert("YieldingNotifier: Failed to cancel", junk == noErr);
  133.             }
  134.             break;
  135.         default:
  136.             // do nothing
  137.             break;
  138.     }
  139. }
  140.  
  141. /////////////////////////////////////////////////////////////////////
  142.  
  143. static void SetDefaultEndpointModes(EndpointRef ep)
  144.     // This routine sets the supplied endpoint into the default
  145.     // mode used in this application.  The specifics are:
  146.     // blocking, synchronous, and using synch idle events with
  147.     // the standard YieldingNotifier.
  148. {
  149.     OSStatus junk;
  150.     
  151.     junk = OTSetBlocking(ep);
  152.     OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
  153.     junk = OTSetSynchronous(ep);
  154.     OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
  155.     junk = OTInstallNotifier(ep, &YieldingNotifier, ep);
  156.     OTAssert("SetDefaultEndpointModes: Could not install notifier", junk == noErr);
  157.     junk = OTUseSyncIdleEvents(ep, true);
  158.     OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
  159. }
  160.  
  161. /////////////////////////////////////////////////////////////////////
  162.  
  163. static OSStatus OTSndQ(EndpointRef ep, void *buf, size_t nbytes)
  164.     // My own personal wrapper around the OTSnd routine that cleans
  165.     // up the error result.
  166. {
  167.     OTResult bytesSent;
  168.     
  169.     bytesSent = OTSnd(ep, buf, nbytes, 0);
  170.     if (bytesSent >= 0) {
  171.     
  172.         // Because we're running in synchronous blocking mode, OTSnd
  173.         // should not return until it has sent all the bytes unless it
  174.         // gets an error.  If it does, we want to hear about it.
  175.         OTAssert("OTSndQ: Not enough bytes sent", bytesSent == nbytes);
  176.     
  177.         return (noErr);
  178.     } else {
  179.         return (bytesSent);
  180.     }
  181. }
  182.  
  183. /////////////////////////////////////////////////////////////////////
  184.  
  185. static OSErr FSReadQ(short refNum, long count, void *buffPtr)
  186.     // My own wrapper for FSRead.  Whose bright idea was it for
  187.     // it to return the count anyway!
  188. {
  189.     OSStatus err;
  190.     long tmpCount;
  191.     
  192.     tmpCount = count;
  193.     err = FSRead(refNum, &count, buffPtr);
  194.     
  195.     OTAssert("FSReadQ: Did not read enough bytes", (err != noErr) || (count == tmpCount));
  196.     
  197.     return (err);
  198. }
  199.  
  200. /////////////////////////////////////////////////////////////////////
  201.  
  202. static Boolean StringHasSuffix(const char *str, const char *suffix)
  203.     // Returns true if the end of str is suffix.
  204. {
  205.     Boolean result;
  206.     
  207.     result = false;
  208.     if ( OTStrLength(str) >= OTStrLength(suffix) ) {
  209.         if ( OTStrEqual(str + OTStrLength(str) - OTStrLength(suffix) , suffix) ) {
  210.             result = true;
  211.         }
  212.     }
  213.     
  214.     return (result);
  215. }
  216.  
  217. static OSStatus ExtractRequestedFileName(const char *buffer,
  218.                                             char *fileName, char *mimeType)
  219.     // Assuming that buffer is a C string contain an HTTP request,
  220.     // extract the name of the file that's being requested.
  221.     // Also check to see if the file has one of the common suffixes,
  222.     // and set mimeType appropriately.
  223.     //
  224.     // Obviously this routine should use Internet Config to
  225.     // map the file type/creator/extension to a MIME type,
  226.     // but I don't want to complicate the sample with that code.
  227. {
  228.     OSStatus err;
  229.     
  230.     // Default the result to empty.
  231.     fileName[0] = 0;
  232.     
  233.     // Scan the request looking for the fileName.  Obviously this is not
  234.     // a very good validation of the request, but this is an OT sample,
  235.     // not an HTTP one.  Also note that we require HTTP/1.0, but some
  236.     // ancient clients might just generate "GET %s<cr><lf>"
  237.     
  238.     (void) sscanf(buffer, "GET %s HTTP/1.0", fileName);
  239.     
  240.     // If the file name is still blank, scanf must have failed.
  241.     // Note that I don't rely on the result from scanf because in a
  242.     // previous life I learnt to mistrust it.
  243.     
  244.     if (fileName[0] == 0) {
  245.         err = -1;
  246.     } else {
  247.     
  248.         // So the request is cool.  Normalise the file name.
  249.         // Requests for the root return "index.html".
  250.         
  251.         if ( OTStrEqual(fileName, "/") ) {
  252.             OTStrCopy(fileName, "index.html");
  253.         }
  254.         
  255.         // Remove the prefix slash.  Note that we don't deal with
  256.         // "slashes" embedded in the fileName, so we don't handle
  257.         // any directories other than the root.  This would be
  258.         // easy to do, but again this is not an HTTP sample.
  259.         
  260.         if ( fileName[0] == '/' ) {
  261.             BlockMoveData(&fileName[1], &fileName[0], OTStrLength(fileName));
  262.         }
  263.     
  264.         // Set mimeType based on the file's suffix.
  265.         
  266.         if ( StringHasSuffix(fileName, ".html") ) {
  267.             OTStrCopy(mimeType, "text/html");
  268.         } else if ( StringHasSuffix(fileName, ".gif") ) {
  269.             OTStrCopy(mimeType, "image/gif");
  270.         } else if ( StringHasSuffix(fileName, ".jpg") ) {
  271.             OTStrCopy(mimeType, "image/jpeg");
  272.         } else {
  273.             OTStrCopy(mimeType, "text/plain");
  274.         }
  275.         err = noErr;
  276.     }
  277.     
  278.     #if qDebug
  279.         printf("ExtractRequestedFileName: Returning %d, “%s”, “%s”\n", err, fileName, mimeType);
  280.     #endif
  281.     
  282.     return (err);
  283. }
  284.  
  285. /////////////////////////////////////////////////////////////////////
  286.  
  287. // The worker thread reads characters one at a time from the endpoint
  288. // and uses the following state machine to determine when the request is
  289. // finished.  For HTTP/1.0 requests, the request is terminated by
  290. // two consecutive CR LF pairs.  Each time we read one of the appropriate
  291. // characters we increment the state until we get to kDone, at which
  292. // point we go off to process the request.
  293.  
  294. enum {
  295.     kWorkerWaitingForCR1,
  296.     kWorkerWaitingForLF1,
  297.     kWorkerWaitingForCR2,
  298.     kWorkerWaitingForLF2,
  299.     kWorkerDone
  300. };
  301.  
  302. // This is the size of the transfer buffer that each worker thread
  303. // allocates to read file system data and write network data.
  304.  
  305. enum {
  306.     kTransferBufferSize = 4096
  307. };
  308.  
  309. // WorkerContext holds the information needed by a worker endpoint to
  310. // operate.  A WorkerContext is created by the listener endpoint
  311. // and passed as the thread parameter to the worker thread.  If the
  312. // listener successfully does this, it's assumed that the worker
  313. // thread has taken responsibility for freeing the context.
  314.  
  315. struct WorkerContext {
  316.     EndpointRef worker;
  317.     short vRefNum;
  318.     long dirID;
  319. };
  320. typedef struct WorkerContext WorkerContext, *WorkerContextPtr;
  321.  
  322. // The two buffers hold standard HTTP responses.  The first is the 
  323. // default text we spit out when we get an error.  The second is
  324. // the header that we use when we successfully field a request.
  325. // Again note that this sample is not about HTTP, so these responses
  326. // are probably not particularly compliant to the HTTP protocol.
  327.  
  328. char gDefaultOutputText[] = "HTTP/1.0 200 OK\15\12Content-Type: text/html\15\12\15\12<H1>Say what!</H1><P>\15\12Error Number (%d), Error Text (%s)";
  329. char gHTTPHeader[] = "HTTP/1.0 200 OK\15\12Content-Type: %s\15\12\15\12";
  330.  
  331. /////////////////////////////////////////////////////////////////////
  332.  
  333. static OSStatus ReadHTTPRequest(EndpointRef worker, char *buffer)
  334.     // This routine reads the HTTP request from the worker endpoint,
  335.     // using the state machine described above, and puts it into the
  336.     // indicated buffer.  The buffer must be at least kTransferBufferSize
  337.     // bytes big.
  338.     //
  339.     // This is pretty feeble
  340.     // code (reading data one byte at a time is bad for performance),
  341.     // but it works and I'm not quite sure how to fix it.  Perhaps
  342.     // OTCountDataBytes?
  343.     //
  344.     // Also, the code does not support with requests bigger than
  345.     // kTransferBufferSize.  In practise, this isn't a problem.
  346. {
  347.     OSStatus err;
  348.     long bufferIndex;
  349.     int state;
  350.     char ch;
  351.     OTResult bytesReceived;
  352.     OTFlags junkFlags;
  353.     
  354.     OTAssert("ReadHTTPRequest: What endpoint?", worker != nil);
  355.     OTAssert("ReadHTTPRequest: What buffer?", buffer != nil);
  356.     
  357.     bufferIndex = 0;
  358.     state = kWorkerWaitingForCR1;
  359.     do {    
  360.         bytesReceived = OTRcv(worker, &ch, sizeof(char), &junkFlags);
  361.         if (bytesReceived >= 0) {
  362.             OTAssert("ReadHTTPRequest: Didn't read the expected number of bytes", bytesReceived == sizeof(char));
  363.             
  364.             err = noErr;
  365.  
  366.             // Put the character into the buffer.
  367.             
  368.             buffer[bufferIndex] = ch;
  369.             bufferIndex += 1;
  370.             
  371.             // Check that we still have space to include our null terminator.
  372.             
  373.             if (bufferIndex >= kTransferBufferSize) {
  374.                 err = -1;
  375.             }
  376.             
  377.             // Do the magic state machine.  Note the use of
  378.             // hardwired numbers for CR and LF.  This is correct
  379.             // because the Internet standards say that these
  380.             // numbers can't change.  I don't use \n and \r
  381.             // because these values change between various C
  382.             // compilers on the Mac.
  383.             
  384.             switch (ch) {
  385.                 case 13:
  386.                     switch (state) {
  387.                         case kWorkerWaitingForCR1:
  388.                             state = kWorkerWaitingForLF1;
  389.                             break;
  390.                         case kWorkerWaitingForCR2:
  391.                             state = kWorkerWaitingForLF2;
  392.                             break;
  393.                         default:
  394.                             state = kWorkerWaitingForCR1;
  395.                             break;
  396.                     }
  397.                     break;
  398.                 case 10:
  399.                     switch (state) {
  400.                         case kWorkerWaitingForLF1:
  401.                             state = kWorkerWaitingForCR2;
  402.                             break;
  403.                         case kWorkerWaitingForLF2:
  404.                             state = kWorkerDone;
  405.                             break;
  406.                         default:
  407.                             state = kWorkerWaitingForCR1;
  408.                             break;
  409.                     }
  410.                     break;
  411.                 default:
  412.                     state = kWorkerWaitingForCR1;
  413.                     break;
  414.             }
  415.         } else {
  416.             err = bytesReceived;
  417.         }
  418.     } while ( err == noErr && state != kWorkerDone );
  419.  
  420.     if (err == noErr) {
  421.         // Append the null terminator that turns the HTTP request into a C string.
  422.         buffer[bufferIndex] = 0;
  423.     }
  424.  
  425.     return (err);        
  426. }
  427.  
  428. /////////////////////////////////////////////////////////////////////
  429.  
  430. static OSStatus CopyFileToEndpoint(const FSSpec *fileSpec, char *buffer, EndpointRef worker)
  431.     // Copy the file denoted by fileSpec to the endpoint.  buffer is a
  432.     // temporary buffer of size kTransferBufferSize.  Initially buffer
  433.     // contains a C string that is the HTTP header to output.  After that,
  434.     // the routine uses buffer as temporary storage.  We do this because
  435.     // we want any errors opening the file to be noticed before we send
  436.     // the header saying that the request went through successfully.
  437. {
  438.     OSStatus err;
  439.     OSStatus junk;
  440.     long bytesToSend;
  441.     long bytesThisTime;
  442.     short fileRefNum;
  443.     
  444.     err = FSpOpenDF(fileSpec, fsRdPerm, &fileRefNum);
  445.     if (err == noErr) {
  446.         err = GetEOF(fileRefNum, &bytesToSend);
  447.         
  448.         // Write the HTTP header out to the endpoint.
  449.         
  450.         if (err == noErr) {
  451.             err = OTSndQ(worker, buffer, OTStrLength(buffer));
  452.         }
  453.         
  454.         // Copy the file in kTransferBufferSize chunks to the endpoint.
  455.         
  456.         while (err == noErr && bytesToSend > 0) {
  457.             if (bytesToSend > kTransferBufferSize) {
  458.                 bytesThisTime = kTransferBufferSize;
  459.             } else {
  460.                 bytesThisTime = bytesToSend;
  461.             }
  462.             err = FSReadQ(fileRefNum, bytesThisTime, buffer);
  463.             if (err == noErr) {
  464.                 err = OTSndQ(worker, buffer, bytesThisTime);
  465.             }
  466.             bytesToSend -= bytesThisTime;
  467.         }
  468.         
  469.         // Clean up.
  470.         junk = FSClose(fileRefNum);
  471.         OTAssert("WorkerThreadProc: Could not close file", junk == noErr);
  472.     }
  473.     
  474.     return (err);
  475. }
  476.  
  477. /////////////////////////////////////////////////////////////////////
  478.  
  479. static pascal OSStatus WorkerThreadProc(WorkerContextPtr context)
  480.     // This routine is the starting routine for the worker thread.
  481.     // The thread is responsible for reading an HTTP request from
  482.     // an endpoint, processing the requesting and writing the results
  483.     // back to the endpoint.
  484. {
  485.     OSStatus err;
  486.     OSStatus junk;
  487.     char *buffer = nil;
  488.     char *errStr;
  489.     char fileName[256];
  490.     char mimeType[256];
  491.     FSSpec fileSpec;
  492.     
  493.     printf("WorkerThreadProc: Starting\n");
  494.     fflush(stdout);
  495.     OTAssert("WorkerThreadProc: Context is nil!", context != nil);
  496.     OTAssert("WorkerThreadProc: Worker endpoint is nil!", context->worker != nil);
  497.  
  498.     // Allocate the transfer buffer in the heap.
  499.     
  500.     err = noErr;
  501.     buffer = OTAllocMem(kTransferBufferSize);
  502.     if (buffer == nil) {
  503.         err = kENOMEMErr;
  504.     }
  505.  
  506.     // Read the request into the transfer buffer.
  507.     
  508.     if (err == noErr) {
  509.         err = ReadHTTPRequest(context->worker, buffer);
  510.     }
  511.     
  512.     if (err == noErr) {
  513.  
  514.         // Get the requested file name (and it's mimeType) from the
  515.         // HTTP request in the transfer buffer.
  516.         
  517.         err = ExtractRequestedFileName(buffer, fileName, mimeType);
  518.         
  519.         if (err == noErr) {
  520.  
  521.             // Create the appropriate HTTP response in the buffer.
  522.             
  523.             sprintf(buffer, gHTTPHeader, mimeType);
  524.  
  525.             // Copy the file (with preceding HTTP header) to the endpoint.
  526.             
  527.             (void) FSMakeFSSpec(context->vRefNum, context->dirID, C2PStr(fileName), &fileSpec);
  528.             err = CopyFileToEndpoint(&fileSpec, buffer, context->worker);
  529.         }
  530.         
  531.         // Handle any errors by sending back an appropriate error header.
  532.         
  533.         if (err != noErr) {
  534.             switch (err) {
  535.                 case fnfErr:
  536.                     errStr = "File Not Found";
  537.                     break;
  538.                 default:
  539.                     errStr = "Unknown Error";
  540.                     break;
  541.             }
  542.             sprintf(buffer, gDefaultOutputText, err, errStr);
  543.             err = OTSndQ(context->worker, buffer, OTStrLength(buffer));
  544.         }
  545.     }
  546.     
  547.     // Shut down the endpoint and clean up the WorkerContext.
  548.     
  549.     if (err == noErr) {
  550.         err = OTSndOrderlyDisconnect(context->worker);
  551.         if (err == noErr) {
  552.             err = OTRcvOrderlyDisconnect(context->worker);
  553.         }
  554.     }
  555.  
  556.     junk = OTCloseProvider(context->worker);
  557.     OTAssert("StartHTTPServer: Could not close listener", junk == noErr);
  558.     
  559.     OTFreeMem(context);
  560.  
  561.     if (buffer != nil) {
  562.         OTFreeMem(buffer);
  563.     }
  564.  
  565.     printf("WorkerThreadProc: Stopping with final result %d.\n", err);
  566.     fflush(stdout);
  567.     
  568.     return (noErr);
  569. }
  570.  
  571. /////////////////////////////////////////////////////////////////////
  572.  
  573. OSStatus RunHTTPServer(InetHost ipAddr, short vRefNum, long dirID)
  574.     // This routine runs an HTTP server.  It doesn't return until
  575.     // someone sets gQuitNow, so you should most probably call this
  576.     // routine on its own thread.  ipAddr is the IP address that
  577.     // the server listens on.  Specify kOTAnyInetAddress to listen
  578.     // on all IP addresses on the machine; specify an IP address
  579.     // to listen on a specific address.  vRefNum and dirID point
  580.     // to the root directory of the HTTP information to be served.
  581.     //
  582.     // The routine creates a listening endpoint and listens for connection 
  583.     // requests on that endpoint.  When a connection request arrives, it creates 
  584.     // a new worker thread (with accompanying endpoint) and accepts the connection
  585.     // on that thread.
  586.     //
  587.     // Note the use of the "tilisten" module which prevents multiple
  588.     // simultaneous T_LISTEN events coming from the transport provider,
  589.     // thereby greatly simplifying the listen/accept sequence.
  590. {
  591.     OSStatus err;
  592.     EndpointRef listener;
  593.     TBind bindReq;
  594.     InetAddress ipAddress;
  595.     InetAddress remoteIPAddress;
  596.     TCall call;
  597.     ThreadID workerThread;
  598.     OSStatus junk;
  599.     WorkerContextPtr workerContext;
  600.     TEndpointInfo Info;
  601.     char    buf[128];
  602.     
  603.     // display IP address in String
  604.     OTInetHostToString(ipAddr, buf);
  605.     printf("HTTP Server on <%s> Starting.\n", buf);
  606.  
  607.     fflush(stdout);
  608.  
  609.     // Create the listen endpoint.
  610.     
  611.     // RRK comments added 8/27/97
  612.     // In order for the IP address to be re-used after quitting this sample program and
  613.     // restarting it, the "ReuseAddr" option must be set.
  614.     // One should be able to set the "ReuseAddr" option as part of the configuration string
  615.     // however, if you try to do this along with specifying the use of the tilisten
  616.     // module, the following code hangs the system hard.  As an alternative, the 
  617.     // endpoint is created with the tilisten module layered above tcp.  After that the
  618.     // OTOptionManagement call is made to set this option.
  619.     // RRK Comments end
  620.     
  621.     //listener = OTOpenEndpoint(OTCreateConfiguration("tilisten,tcp(ReuseAddr=1)"), 0, nil, &err);
  622.     listener = OTOpenEndpoint(OTCreateConfiguration("tilisten,tcp"), 0, &Info, &err);
  623.     
  624.     // RRK addition 8/27/97
  625.     // set the ReuseAddr option
  626.     if (err == noErr) {
  627.         junk = DoNegotiateIPReuseAddrOption(listener, true);
  628.         OTAssert("Unable to negotiate raw mode for listener endpoint", junk == noErr);
  629.     }    
  630.     // end RRK addition 8/27/97
  631.  
  632.     // Set the endpoint mode and bind it to the appropriate IP address.
  633.     
  634.     if (err == noErr) {
  635.         SetDefaultEndpointModes(listener);
  636.         OTInitInetAddress(&ipAddress, 80, ipAddr);    // port & host ip
  637.         bindReq.addr.buf = (UInt8 *) &ipAddress;
  638.         bindReq.addr.len = sizeof(ipAddress);
  639.         bindReq.qlen = 1;
  640.         err = OTBind(listener, &bindReq, nil);
  641.     }
  642.     
  643.     while (err == noErr) {
  644.  
  645.         // Listen for connection attempts...
  646.         
  647.         OTMemzero(&call, sizeof(TCall));
  648.         call.addr.buf = (UInt8 *) &remoteIPAddress;
  649.         call.addr.maxlen = sizeof(remoteIPAddress);
  650.         err = OTListen(listener, &call);
  651.  
  652.         // ... then spool a worker thread for this connection.
  653.         
  654.         if (err == noErr) {
  655.         
  656.             // Create the worker context.
  657.         
  658.             workerThread = kNoThreadID;
  659.             workerContext = OTAllocMem(sizeof(WorkerContext));
  660.             if (workerContext == nil) {
  661.                 err = kENOMEMErr;
  662.             } else {
  663.                 workerContext->worker = nil;
  664.                 workerContext->vRefNum = vRefNum;
  665.                 workerContext->dirID = dirID;
  666.             }
  667.             
  668.             // Open the worker endpoint.
  669.             
  670.             if (err == noErr) {
  671.                 workerContext->worker = OTOpenEndpoint(OTCreateConfiguration("tcp"), 0, nil, &err);
  672.                 if (err == noErr) {
  673.                     SetDefaultEndpointModes(workerContext->worker);
  674.                 }
  675.             }
  676.             
  677.             // Create the worker thread.
  678.             
  679.             if (err == noErr) {
  680.                 err = NewThread(kCooperativeThread,
  681.                                 (ThreadEntryProcPtr) WorkerThreadProc, workerContext,
  682.                                 0, kNewSuspend | kCreateIfNeeded,
  683.                                 nil,
  684.                                 &workerThread);
  685.             }
  686.             
  687.             // Accept the connection on the thread.
  688.             
  689.             if (err == noErr) {
  690.                 err = OTAccept(listener, workerContext->worker, &call);
  691.             }
  692.             
  693.             // Schedule the thread for execution.
  694.             
  695.             if (err == noErr) {
  696.                 err = SetThreadState(workerThread, kReadyThreadState, kNoThreadID);
  697.             }
  698.             
  699.             // Clean up on error.
  700.             
  701.             if (err != noErr) {
  702.                 if (workerContext != nil) {
  703.                     if (workerContext->worker != nil) {
  704.                         junk = OTCloseProvider(workerContext->worker);
  705.                         OTAssert("StartHTTPServer: Could not close worker", junk == noErr);
  706.                     }
  707.                     OTFreeMem(workerContext);
  708.                 }
  709.                 if (workerThread != kNoThreadID) {
  710.                     junk = DisposeThread(workerThread, nil, true);
  711.                     OTAssert("StartHTTPServer: DisposeThread failed", junk == noErr);
  712.                 }
  713.                 printf("StartHTTPServer: Failed to spool worker, error %d.\n", err);
  714.                 fflush(stdout);
  715.                 err = noErr;
  716.             }
  717.         }
  718.     }
  719.     
  720.     // Clean up the listener endpoint.
  721.     
  722.     if (listener != nil) {
  723.         junk = OTCloseProvider(listener);
  724.         OTAssert("StartHTTPServer: Could not close listener", junk == noErr);
  725.     }
  726.  
  727.     printf("HTTP Server on %08x: Stopping.\n", ipAddr);
  728.     fflush(stdout);
  729.     
  730.     return (err);
  731. }
  732.